package com.questions.helper.service;

import static com.questions.helper.util.Utils.ass;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.questions.helper.MainActivity;
import com.questions.helper.application.QuestionsHelperApplication;
import com.questions.helper.model.Answer;
import com.questions.helper.model.Questions;
import com.questions.helper.util.Utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MyPoiService extends Service {
    QuestionsHelperApplication questionsHelperApplication;
    File file;
    public List<Questions> excData(File file) {
        this.file = file;
        try (Workbook book = new XSSFWorkbook(file)){
           return exc(book);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<Questions> exc(Workbook book){
        List<Questions> exs = new ArrayList<>();
        Sheet sheet = book.getSheetAt(0);
        int lastRow = sheet.getLastRowNum();
        //题干（必填）	题型 （必填）	选项 A	选项 B	选项 C	选项 D	选项E	选项F	选项G	选项H	正确答案（必填）
        for(int i=1;i<=lastRow;i++){
            Questions questions = new Questions();
            Row row  = sheet.getRow(i);
            questions.setTitleText(Utils.formText(row.getCell(0).getStringCellValue()));
            questions.setQuestionsType(row.getCell(1).getStringCellValue());
            questions.setAnswersSort(row.getCell(10).getStringCellValue());
            List<Answer> answerList = new ArrayList<>();
            for(int j = 2;j<10;j++){
                Answer answer = new Answer();
                Cell cell =  row.getCell(j);
                cell.setCellType(CellType.STRING);
                String answerText = Utils.formText(cell.getStringCellValue());
                if (!answerText.isEmpty()){
                    answer.setAnswerSort(ass[j-2]);
                    answer.setAnswerOrder(j-2);
                    if(questions.getAnswersSort().contains(answer.getAnswerSort())){
                        answer.setCorrect(Answer.CORRECT_YES);
                    }
                    answer.setTitleText(answerText);
                    answerList.add(answer);
                }

            }
            questions.setAnswers(answerList);
            exs.add(questions);
        }
        return exs;
    }

    Thread thread;

    /**
     * 解除绑定时调用
     */
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intentBroadcastReceiver = new Intent();
        String filePath = intent.getStringExtra("file");
        if(filePath==null|| filePath.isEmpty()){
            intentBroadcastReceiver.setAction(MainActivity.ACTION_SERVICE_NEED_NULL);
            sendBroadcast(intentBroadcastReceiver);
        }else {
            thread = new Thread(()->{
                Log.i(this.getPackageName(),filePath);
                try {
                    List<Questions> questions = excData(new File(filePath));
                    questionsHelperApplication.getLegalknowledgeSQLite().saveDate(questions);
                    intentBroadcastReceiver.setAction(MainActivity.ACTION_SERVICE_NEED);
                }catch (RuntimeException e){
                    Log.e(this.getPackageName(), Objects.requireNonNull(e.getMessage()));
                    intentBroadcastReceiver.putExtra(MainActivity.TOAST_DATA,e.getMessage());
                    intentBroadcastReceiver.setAction(MainActivity.ACTION_SERVICE_NEED_NULL);
                }
                sendBroadcast(intentBroadcastReceiver);
            });
            thread.start();
        }
        return super.onStartCommand(intent, flags, startId);


    }

    @Override
    public void onCreate() {
        super.onCreate();
        questionsHelperApplication = QuestionsHelperApplication.questionsHelperApplication;
    }

    /**
     * 销毁调用
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
